package com.itheima.case2.web;

import com.itheima.case2.pojo.po.UserLogin;
import com.itheima.case2.service.impl.UserLoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码并获取前端传入的参数
        //request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        //2.创建User对象存储对应参数数据
        UserLogin user = new UserLogin(username, password);
        //设置域对象，登陆了才可以访问其他资源
        request.getSession().setAttribute("user",user);
        //获取Session中的验证码
        String checkCode = (String) request.getSession().getAttribute("checkCode");
        //3.设置响应编码
        //response.setContentType("text/html;charset=utf-8");
        //比较验证码是否输入正确
        if (checkCode.equalsIgnoreCase(code)){
            //验证码输入正确
            //4.创建UserService对象调用对应登录方法(返回User类型)
            UserLoginServiceImpl userService = new UserLoginServiceImpl();
            UserLogin loginUser = userService.login(user);
            if (loginUser!=null){
                //5.返回响应给前端
                response.getWriter().write("true");
            } else {
                response.getWriter().write("false");
            }
        }else {
            response.getWriter().print("false");
        }

    }
}